package controller

import (
	"admin-server/libs"
	"admin-server/models"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"net/http"
)

type loginForm struct {
	Username string `json:"username" binding:"required"`
	Password string `json:"password" binding:"required"`
}

type AccountLoginRespType struct {
	Username    string `json:"username"`
	AccessToken string `json:"access_token"`
	ExpireIn    int    `json:"expire_in"`
}

var (
	admin models.Admin
)

// 账号登录
func AccountLogin(ctx *gin.Context) {
	var (
		res  AccountLoginRespType
		form loginForm
	)
	db := libs.GetDb()
	if err := ctx.ShouldBind(&form); err != nil {
		ctx.Status(http.StatusBadRequest)
		return
	}

	// fmt.Println(form.Username)
	// fmt.Println(form.Password)

	err := db.
		Where("username=?", form.Username).
		Select("id,nickname,username,password").
		First(&admin).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		ctx.JSON(200, gin.H{"error": "账号不存在"})
		return
	}
	if !libs.PasswordVerify(form.Password, admin.Password) {
		ctx.JSON(200, gin.H{"error": "密码错误"})
		return
	}

	res.Username = admin.Username
	res.ExpireIn = 7200
	res.AccessToken = libs.CreateAccessToken(int(admin.ID), res.ExpireIn)

	//redisErr := libs.RedisSet("access_token:" + res.Username, res.AccessToken, res.ExpireIn)
	//if redisErr != nil {
	//	panic(redisErr)
	//}
	// res.AccessToken =

	ctx.JSON(200, res)
}

// 当前登录信息
func CurrentAccountInfo(ctx *gin.Context) {
	info := GetAccountInfo(ctx)

	ctx.JSON(200, gin.H{
		"info": info,
	})
}
